package com.jd.controller;

import com.jd.bo.UserBO;
import com.jd.pojo.User;
import com.jd.service.UserService;
import com.jd.test.event.UserService2;
import com.jd.utils.CookieUtils;
import com.jd.utils.JDJSONResult;
import com.jd.utils.JsonUtils;
import com.jd.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.scripts.JD;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Api(value = "注册登录",tags = {"用于注册登录的相关接口"})
@RestController
@RequestMapping("passport")
public class PassportController {

    @Autowired
    UserService userService;

    @ApiOperation(value = "用户名是否存在",notes = "用户名是否存在",httpMethod = "GET")
    @GetMapping("/usernameIsExist")
    public JDJSONResult usernameIsExist(@RequestParam  String username){
        //1、判断用户名不能为空
        if(StringUtils.isBlank(username)){
           return JDJSONResult.errorMsg("用户名不能为空");
        }
        //2、查找注册的用户名是否存在
       boolean isExist= userService.queryUsernameIsExist(username);
        if(isExist){
            return JDJSONResult.errorMsg("用户名已经存在");
        }
        //3、请求成功，用户名没有重复
        return JDJSONResult.ok();
    }

    @ApiOperation(value = "用户注册",notes = "用户注册",httpMethod = "POST")
    @PostMapping("/regist")
    public JDJSONResult regist(@RequestBody UserBO userBO,
                               HttpServletRequest request, HttpServletResponse response){
        String username=userBO.getUsername();
        String password=userBO.getPassword();
        String confirmPwd=userBO.getConfirmPassword();

        //0 判定用户名或密码必须不为空
        if(StringUtils.isBlank(username)||
                StringUtils.isBlank(password)||
                StringUtils.isBlank(confirmPwd)){
            return JDJSONResult.errorMsg("用户名或密码不能为空");
        }

        //1、查询用户名是否存在
        boolean isExist=userService.queryUsernameIsExist(username);
        if(isExist){
            return JDJSONResult.errorMsg("用户名已经存在");
        }
        // 2、密码长度不能少于6位
        if(password.length()<6){
            return JDJSONResult.errorMsg("密码长度不能少于6");
        }

        //3 判定两次密码是否一致
        if(!password.equals(confirmPwd)){
            return JDJSONResult.errorMsg("两次密码不一致");
        }
        //4、实现注册
        User userResult=userService.createUser(userBO);
        userResult=setNullProperty(userResult);
        //把用户信息存储到cookie
        CookieUtils.setCookie(request,response,"user",
                JsonUtils.objectToJson(userResult),true);


        //TODO 生成用户token，存入redis会话
        //TODO 同步购物车数据

        return JDJSONResult.ok();
    }


    /**
     * 登录的实现方式，采用cookie的形式，把用户信息加密存储到cookie
     * @param userBO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "用户登录",notes = "用户登录",httpMethod = "POST")
    @PostMapping("/login")
    public JDJSONResult login(@RequestBody UserBO userBO,
     HttpServletRequest request, HttpServletResponse response) throws  Exception{
        String username=userBO.getUsername();
        String password=userBO.getPassword();

        //0 判定用户名或密码必须不为空
        if(StringUtils.isBlank(username)||
                StringUtils.isBlank(password)){
            return JDJSONResult.errorMsg("用户名或密码不能为空");
        }

        //2、实现用户登录
        User userResult=userService.queryUserForLogin(userBO.getUsername(), MD5Utils.getMD5Str(userBO.getPassword()));
        if(userResult==null){
            return JDJSONResult.errorMsg("用户名或密码不正确");
        }
        userResult=setNullProperty(userResult);
        //把用户信息存储到cookie
        CookieUtils.setCookie(request,response,"user",
                JsonUtils.objectToJson(userResult),true);


        //TODO 生成用户token，存入redis会话
        //TODO 同步购物车数据



        return JDJSONResult.ok(userResult);
    }

    @ApiOperation(value = "用户退出登录",notes = "用户退出登录",httpMethod = "POST")
    @PostMapping("/logout")
    public JDJSONResult logout(@RequestParam String userId,
                              HttpServletRequest request, HttpServletResponse response) throws  Exception{
        //清楚用户相关信息cookie
        CookieUtils.deleteCookie(request,response,"user");

        //TODO  用户退出登录，需要清空购物车
        //TODO 分布式会话中需要清除用户数据

        return JDJSONResult.ok();
    }

    private User setNullProperty(User userResult){
        userResult.setPassword(null);
        userResult.setMobile(null);
        userResult.setEmail(null);
        userResult.setCreatedTime(null);
        userResult.setUpdatedTime(null);
        userResult.setBirthday(null);
        return userResult;
    }
}
